package it.uni.bo.monitoring.sla.chain.latency;

import it.uni.bo.monitoring.protocol.unmarshaller.EventInfo;
import it.uni.bo.monitoring.sla.context.ComponentManager;

import java.util.HashMap;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import static it.uni.bo.monitoring.service.StaticFields.INB;
import static it.uni.bo.monitoring.service.StaticFields.QUERY_SQL_VIOLATION;

public class LatencyManager implements ComponentManager{

	private Latency latency;
	private HashMap<String, EventInfo> eventMap;
	private SessionFactory factory;
	private Logger l;
	private String description;
	private final static String DESC_VIOLATION="LATENCY";
	
	public LatencyManager(Latency latency, SessionFactory factory) {
		l = Logger.getLogger(this.getClass());
		this.latency=latency;
		this.factory=factory;
		eventMap=new HashMap<String, EventInfo>();
	}
	public void makeTrans(EventInfo ei) {
		if(	(	latency.getOperationName().size()>0) && 
				!(latency.getOperationName().contains(ei.getOperationName())
				))
			return;
		//calcolo la chiave composta da Nome Operazione, Sessione e numero di sequenza
		String key=ei.getOperationName()+ei.getSession()+ei.getSeqNumber();
		if(ei.getDirection()==(Character.forDigit(INB & 0xFF, 2)))
			eventMap.put(key, ei);
		else {
			if(eventMap.containsKey(key)){
				EventInfo eiRequest = eventMap.get(key);
				long responseTime=ei.getTimestamp()-eiRequest.getTimestamp();
				//System.out.println("responseTime.."+responseTime);
				if (responseTime>latency.getMaxDuration()) {
					description=DESC_VIOLATION+ " | "+ei.getAppUrl()+ " | "+ei.getNamespace()+ " | "+ei.getOperationName()+" | "+latency.getMaxDuration()+" | "+responseTime+" | "+eiRequest.getTimestamp()+" | "+ei.getTimestamp()+" |";
					l.info(description);

					if(factory!=null){
						Session session=factory.openSession();
						Query query = session.createSQLQuery(QUERY_SQL_VIOLATION);
						query.setString(0, "latency");
						query.setLong(1, ei.getIdSla());
						query.setBinary(2, ei.getIdE());
						query.setString(3, description);
						l.info("Hibernate: "+QUERY_SQL_VIOLATION+" [ latency "+ei.getIdSla()+" "+new String(ei.getIdE())+" "+description+" ]");
						query.executeUpdate();
						if ((session!=null) && (session.isOpen())) 
							session.close(); 
					}
				}
				eventMap.remove(key);
			}
		}
	}

}
